package com.fy.tt.executor.node.word.noun;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.fy.tt.action.TemplateTool;
import com.fy.tt.remote.service.CoreRemoteService;
import com.fy.tt.utils.BandCore;
import lombok.Data;

import java.lang.reflect.InvocationTargetException;
import java.net.URLEncoder;
import java.util.Map;

@Data
public class Band extends Noun {

    CoreRemoteService coreRemoteService = null;

    {
        try {
            coreRemoteService = TemplateTool.getBean(CoreRemoteService.class);
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        } catch (InvocationTargetException e) {
            e.printStackTrace();
        }
    }

    private String bandID;
    private String objID;
    private String text;

    public Band(String text, Map<String, Object> scriptEnvironment) {
            init(text, scriptEnvironment);
    }

    public void init(String text, Map<String, Object> scriptEnvironment) {
        if(text.startsWith("\"")){
            text = text.substring(1, text.length() - 1);
        }else{
            text = text.trim();
        }

        try {
            JSONObject jsonObject = coreRemoteService.getBandByBandName(text);
            if (((int) jsonObject.get("total")) == 0) {
                throw new RuntimeException("查不到该帮区信息："+text);
            }
            JSONArray rows = jsonObject.getJSONArray("rows");
            String objID = (String) rows.getJSONObject(0).get("objID");
            String bandID = (String) rows.getJSONObject(0).get("bandID");
            this.objID = objID;
            this.bandID = bandID;
        } catch (Exception e) {
            e.printStackTrace();
        }

    }

    @Override
    public boolean run(String methodName) {
        return super.run(methodName);
    }

    public static void main(String[] args) throws Exception {
        String text = "2019级梁子豪个人工作区";
        String query = "{\"name\":\"%s\"}";
        query = String.format(query,text);
        String encode = URLEncoder.encode(query, "UTF-8");
        String httpurl = "https://www.wetoband.com/core//core/v4/band?format=json&gid=%s&query=%s&aid=21419389378723787447";
        String accessToken = BandCore.getAccessToken();
//        String accessToken = "5718362b6ed4193b3dad76a670df24974d1cc673dd93e1000b4976669ce7ffdec2505110d02875f83c7108d44e59c157a20957f2b74cbe1db21706ea255b151d";
        httpurl=String.format(httpurl,"314539854",encode);
        String s = BandCore.doGetWithAccessToken(httpurl, accessToken);
        System.out.println(s);
        JSONObject jsonObject = JSON.parseObject(s);
        if (((int) jsonObject.get("total")) ==0) {
            throw new RuntimeException("查不到该帮区信息："+text);
        }
        JSONArray rows = jsonObject.getJSONArray("rows");
        String objID = (String) rows.getJSONObject(0).get("objID");
        System.out.println("objID = " + objID);
    }
}
